package com.realm;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.entity.Menu;
import com.entity.User;
import com.service.MenusService;
import com.service.UserService;

public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private MenusService menusService;

    public MyRealm() {
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
	// TODO Auto-generated method stub
	System.out.println("======================获取权限========================");
	String username = (String) arg0.fromRealm(getName()).iterator().next();
	User user=userService.findUser(username);
	List<Menu> menus= menusService.menusBase(user);
	if(menus!=null&&menus.size()>0){
	    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	    for (Menu menu : menus) {
		info.addStringPermission(menu.getRole());
	    }
	    System.out.println("=========================结束获取权限====================");
	    System.out.println(user+user.getUsername()+":"+user.getId());
	    return info;
	}
	System.out.println("=========================结束获取权限====================");
	return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
	    AuthenticationToken arg0) throws AuthenticationException {
	// TODO Auto-generated method stub
	UsernamePasswordToken token = (UsernamePasswordToken) arg0;
	System.out.println("aaaaaaaaaaaaaaaaa");
	User user = userService.findUser(token.getUsername());
	System.out.println(user);
	
	if (user != null) {
	    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
		    user.getUsername(), user.getPassword(), getName());
	    System.out.println("aaaaaaaa------aaaaaaaaa");
	    return info;

	}
	return null;
    }

}
